import React, {useCallback, useEffect, useState} from "react"
import {observerDashboardPageWrapper} from "./ObserverDashboardPageWrapper";
import {PAGE_START, Pageable} from "../../utils/Page";
import {
    deleteProcurementItem,
    deleteProcurementItemSub, deleteProcurementSupplierPaymentRecord, payProcurement,
    ProcurementDetail, ProcurementSupplierPaymentRequest,
    QueryProcurementPaymentRecordResponse,
    QueryProcurementResponse,
    queryProcurementSupplierPaymentRecords
} from "../../apis/ProcurementApi";
import {Button, Card, ConfigProvider, DatePicker, Descriptions, Form, Input, Table} from "antd";
import {getProcurementSupplierDetail, ProcurementSupplierDetail} from "../../apis/ProcurementSupplierApi";
import DataPageLayout from "../DataPageLayout";
import {AntdTableColumnRenders, mergePaginationAndPageable} from "../../utils/AntdTableUtils";
import {DeleteOutlined} from "@ant-design/icons";
import AuthorizationResource from "../AuthorizationResource";
import FormDrawer from "../FormDrawer";
import {Dayjs} from "dayjs";
import {DateTimeFormatter, OffsetDateTime, ZoneId} from "@js-joda/core";
import Decimal from "decimal.js";
import {
    getProcurementSupplierFeeDetailGroupByMonth,
    ProcurementSupplierFeeDetailGroupByMonthResponse
} from "../../apis/ProcurementSupplierStatisticApi";
import {Column, Line} from "@ant-design/charts";

export interface ProcurementPaymentRecordPageProps {
    supplierId: number
}

const ProcurementPaymentRecordPage: React.FC<ProcurementPaymentRecordPageProps> = ({supplierId}) => {
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryProcurementPaymentRecordResponse[]>([])
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)
    const [totalPaidMoney, setTotalPaidMoney] = useState(0)
    const [totalNeedPaidMoney, setTotalNeedPaidMoney] = useState(0)
    const query = useCallback(() => {
        queryProcurementSupplierPaymentRecords(supplierId, {}).then(response => {
            let data = response.data;
            setData(response.data.content)
            setTotalElements(data.totalElements)
            setTotalPaidMoney(data.totalPaidMoney)
            setTotalNeedPaidMoney(data.totalNeedPaidMoney)
        })
    }, [supplierId, ...pageable.toDependencyList()])
    useEffect(() => {
        query()
    }, [query]);

    const [detail, setDetail] = useState<ProcurementSupplierDetail>()
    useEffect(() => {
        getProcurementSupplierDetail(supplierId).then(response => setDetail(response.data))
    }, [supplierId]);
    const [openRecordDrawer, setOpenRecordDrawer] = useState(false)

    const [statisticByMonthResponse, setStatisticByMonthResponse] = useState<ProcurementSupplierFeeDetailGroupByMonthResponse>()
    useEffect(() => {
        getProcurementSupplierFeeDetailGroupByMonth(supplierId)
            .then(response => {
                setStatisticByMonthResponse(response.data)
            })
    }, []);
    return (
        <>
            {!loading && detail ? <Descriptions title={`${detail.name}账目`}>
                <Descriptions.Item label={"供货商"}>{detail.name}</Descriptions.Item>
                <Descriptions.Item label={"已支付金额"}>{totalPaidMoney}</Descriptions.Item>
                <Descriptions.Item label={"共产生货款"}>{totalNeedPaidMoney}</Descriptions.Item>

                <Descriptions.Item label={"结余"}>{(() => {

                    const diff = new Decimal(totalPaidMoney).minus(totalNeedPaidMoney)
                    if (diff.greaterThan(0)) {
                        return `余${diff}`
                    } else if (diff.lessThan(0)) {
                        return `${diff.abs()}未结`
                    } else {
                        return "已结清"
                    }
                })()}</Descriptions.Item>

            </Descriptions> : null}
            <DataPageLayout rightActions={<>
                <Button type={"primary"} onClick={() => {
                    setOpenRecordDrawer(true)
                }}>记录</Button>
            </>}>
                <ConfigProvider componentSize={"small"}>
                    <Table<QueryProcurementPaymentRecordResponse> loading={loading}
                                                                  dataSource={data} rowKey={"id"}
                                                                  pagination={{
                                                                      current: pageable.page,
                                                                      pageSize: pageable.size,
                                                                      total: totalElements,
                                                                  }} onChange={(pagination, _, sorter) => {
                        setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                    }} columns={[{
                        dataIndex: "money",
                        title: "金额",
                    }, {
                        dataIndex: 'paidDateTime',
                        title: "支付时间",
                        render: AntdTableColumnRenders.dateTimeColumnRender,
                    }, {
                        dataIndex: 'createdDateTime',
                        title: "记录时间",
                        render: AntdTableColumnRenders.dateTimeColumnRender,
                    }, {
                        title: "操作",
                        render: (_, item) => {
                            return <AuthorizationResource
                                authorities={["采购_账目_删除"]}>
                                <Button type={"link"}
                                        danger
                                        onClick={async (event) => {
                                            event.stopPropagation()
                                            await deleteProcurementSupplierPaymentRecord(item.id)
                                            if (data.length === 1 && pageable.page !== PAGE_START) {
                                                setPageable(Pageable.from(pageable, {page: pageable.page - 1}))
                                            } else {
                                                query()
                                            }
                                        }}>
                                    <DeleteOutlined/>
                                    删除
                                </Button>
                            </AuthorizationResource>
                        }
                    }]}/>
                    <Card title={"采购统计"}>
                        {!!statisticByMonthResponse && <Line title={"月采购费用统计"}
                                                               data={statisticByMonthResponse.data.flatMap((it, index, array) => {
                                                                   let label = array.findIndex(item => item.statisticYearMonth.year() === it.statisticYearMonth.year()) === index ? `${it.statisticYearMonth.year()}年${it.statisticYearMonth.monthValue()}月` : `${it.statisticYearMonth.monthValue()}月`;
                                                                   return [{
                                                                       label: label,
                                                                       value: it.procurementFee??0,
                                                                       yearMonth: it.statisticYearMonth,
                                                                       type: "采购"
                                                                   },{
                                                                       label,
                                                                       value:it.returnFee??0,
                                                                       yearMonth: it.statisticYearMonth,
                                                                       type:"退货",
                                                                   }];
                                                               }).filter(it=>!!it)} xField={"label"} yField={"value"} colorField={"type"} seriesField={"type"} axis={{
                            x: {
                                title: "月份"
                            },
                            y: {
                                title: "月采购费用",
                            }
                        }} tooltip={{title: i => i.yearMonth.format(DateTimeFormatter.ofPattern("yyyy年MM月")), }}
                        />}
                    </Card>
                </ConfigProvider>
            </DataPageLayout>

            <FormDrawer<ProcurementSupplierPaymentRequest> open={openRecordDrawer} title={"新增支付记录"}
                                                           onClose={() => setOpenRecordDrawer(false)}
                                                           onConfirm={async values => {
                                                               payProcurement(supplierId, {
                                                                   ...values,
                                                                   paidDateTime: OffsetDateTime.parse((values.paidDateTime as unknown as Dayjs).toJSON())
                                                               }).then(res => {
                                                                   setPageable(Pageable.from(pageable, {page: PAGE_START}))
                                                                   query()
                                                                   setOpenRecordDrawer(false)
                                                               })
                                                           }}>
                <Form.Item label={"金额"} name="money" rules={[{required: true}]}>
                    <Input type={"number"}/>
                </Form.Item>
                <Form.Item label={"支付时间"} name={"paidDateTime"} rules={[{required: true}]}>
                    <DatePicker showTime onOk={(value,) => {
                        console.log(value)
                    }}/>
                </Form.Item>
            </FormDrawer>
        </>
    )
}

export default observerDashboardPageWrapper(ProcurementPaymentRecordPage, "procurements/suppliers/{supplierId}/paymentRecords", "采购账目")
